package com.lagou.dao.impl;

import com.lagou.dao.StudentDao;
import com.lagou.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class StudentDaoImpl implements StudentDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int save(Student student) {
        String sql = "insert into student(name) values (?)";

        return jdbcTemplate.update(sql, student.getName());
    }

    @Override
    public int update(Student student) {
        String sql = "update student set name = ? where id = ?";

        return jdbcTemplate.update(sql, student.getName(), student.getId());
    }

    @Override
    public int delete(int id) {
        String sql = "delete from student where id = ?";

        return jdbcTemplate.update(sql, id);
    }

    @Override
    public Student select(int id) {
        String sql = "select * from student where id = ?";

        List<Student> students = jdbcTemplate.query(sql, new Object[]{id}, new BeanPropertyRowMapper<>(Student.class));
        if (!students.isEmpty()) {
            return students.get(0);
        }

        return null;
    }

    @Override
    public List<Student> selectAll() {
        String sql = "select * from student";

        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Student.class));
    }

}
